//
// Created by Jisam on 2024/7/8.
//
#include <bits/stdc++.h>

#define PSI pair<string,int>
#define PII pair<int,int>
#define x first
#define y second
#define i64 long long
using namespace std;
const int N = 1e5 + 5;
int ans;

void solve() {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> a((n + 1),vector<int>(n+1,0)),
                        b((n + 1),vector<int>(n+1,0)),
                        vis((n + 1),vector<int>(n+1,0));
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            cin >> a[i][j];
        }
    }
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            cin >> b[i][j];
        }
    }
    int no = 0;
    for(int i = 1 ; i <= n ; i ++){
        for(int j = 1; j <= n ; j ++){

            while(a[i][j] !=  b[i][j]){
                if(vis[i][j] == 3) no = 1;
                vis[i][j] ++;
                int k = n + i ,l = n + i;
                while(k >= n || l >= n || a[k][l] == b[k][l]){
                    k --;
                    l --;
                }
                a[i][j] = (a[i][j] + 1) % 3;
                a[k][l] = (a[k][l] + 1) % 3;

                a[n - i + 1][j] = (a[n - i + 1][j] + 2) % 3;
                a[n - k + 1][l] = (a[n - k + 1][l] + 2) % 3;
            }
        }
    }
    if(no) cout <<"NO";
    else cout << "YES";
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int T;
    cin >> T;
    while (T--) {
        solve();
    }
    return 0;
}